package com.chrilwe.pigpig.filesystem.service;

import java.io.IOException;
import java.util.UUID;

import org.csource.common.MyException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import com.chrilwe.pigpig.filesystem.common.ImageEnum;
import com.chrilwe.pigpig.filesystem.common.ex.UnSupportImageTypeException;
import com.chrilwe.pigpig.filesystem.common.util.FastDfsUtil;
import com.chrilwe.pigpig.filesystem.mapper.ImageDetailMapper;

import cn.chrilwe.pigpig.core.model.filesystem.ImageDetail;

/**
 * 
 * @author chrilwe
 * @date 2020-9-11 
 */
@Service
@Transactional
public class ImageFileService {
	
	@Autowired
	protected ImageDetailMapper imageDetailMapper;

	public String uploadImage(MultipartFile image, int userId) throws IOException, MyException {
		String originalFilename = image.getOriginalFilename();
		long imageSize = image.getSize();
		int lastIndexOf = originalFilename.lastIndexOf(".");
		if (lastIndexOf == -1 || lastIndexOf == 0) {
			throw new UnSupportImageTypeException("不支持的图片类型");
		}
		String ext = originalFilename.substring(0, lastIndexOf + 1);
		if (!checkImageFile(ext))
			throw new UnSupportImageTypeException("不支持的图片类型");
		
		ImageDetail imageDetail = doUploadImage(image,ext);
		imageDetail.setImageOriginName(originalFilename);
		imageDetail.setImageSize(image.getSize());
		imageDetail.setStatus(1);
		imageDetail.setUserId(userId);
		imageDetailMapper.insertImageDetail(imageDetail);
		return imageDetail.getImageUrl();
	}

	// 只支持jpg,png,jpeg,gif,icon图片格式
	protected boolean checkImageFile(String ext) {
		if (!ext.equals(ImageEnum.JPG.getName()) && !ext.equals(ImageEnum.GIF.getName())
				&& !ext.equals(ImageEnum.ICON.getName()) && !ext.equals(ImageEnum.PNG.getName())
				&& !ext.equals(ImageEnum.JPEG.getName()))
			return false;
		return true;
	}

	protected ImageDetail doUploadImage(MultipartFile image, String ext) throws IOException, MyException {
		byte[] data = image.getBytes();
		String url = FastDfsUtil.upload(data, ext, null);
		
		ImageDetail imageDetail = new ImageDetail();
		imageDetail.setImageNameExt(ext);
		imageDetail.setImageUrl(url);
		imageDetail.setImageName(url.substring(url.lastIndexOf("/")+1));
		return imageDetail;
	}
	
	public void deleteImage(int imageId) {
		
	}
}
